package com.hzsparrow.ai.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hzsparrow.ai.entity.Conversation;
import com.hzsparrow.ai.entity.User;
import com.hzsparrow.ai.service.ConversationService;
import com.hzsparrow.ai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 对话控制器
 */
@RestController
@RequestMapping("/api/conversation")
public class ConversationController {

    @Autowired
    private ConversationService conversationService;

    @Autowired
    private UserService userService;

    /**
     * 获取用户的所有对话
     */
    @GetMapping("/list")
    public ResponseEntity<?> getUserConversations() {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            List<Conversation> conversations = conversationService.getUserConversations(user.getId());
            return ResponseEntity.ok(conversations);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 分页获取用户的对话
     */
    @GetMapping("/page")
    public ResponseEntity<?> getConversationsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            Page<Conversation> result = conversationService.listConversations(page, size, user.getId());
            
            Map<String, Object> response = new HashMap<>();
            response.put("total", result.getTotal());
            response.put("pages", result.getPages());
            response.put("current", result.getCurrent());
            response.put("size", result.getSize());
            response.put("records", result.getRecords());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 创建新对话
     */
    @PostMapping("/create")
    public ResponseEntity<?> createConversation(@RequestBody Conversation conversation) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 设置用户ID
            conversation.setUserId(user.getId());
            
            // 创建对话
            Conversation created = conversationService.createConversation(conversation);
            return ResponseEntity.ok(created);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 获取对话详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<?> getConversation(@PathVariable Long id) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 获取对话
            Conversation conversation = conversationService.getConversation(id);
            
            // 验证对话是否属于当前用户
            if (conversation == null || !conversation.getUserId().equals(user.getId()) 
                    && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权访问此对话");
            }
            
            return ResponseEntity.ok(conversation);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 通过会话ID获取对话
     */
    @GetMapping("/session/{sessionId}")
    public ResponseEntity<?> getConversationBySessionId(@PathVariable String sessionId) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 获取对话
            Conversation conversation = conversationService.getConversationBySessionId(sessionId);
            
            // 验证对话是否属于当前用户
            if (conversation == null || !conversation.getUserId().equals(user.getId()) 
                    && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权访问此对话");
            }
            
            return ResponseEntity.ok(conversation);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 更新对话标题
     */
    @PutMapping("/title/{sessionId}")
    public ResponseEntity<?> updateConversationTitle(
            @PathVariable String sessionId,
            @RequestBody Map<String, String> body) {
        
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 获取对话
            Conversation conversation = conversationService.getConversationBySessionId(sessionId);
            
            // 验证对话是否属于当前用户
            if (conversation == null || !conversation.getUserId().equals(user.getId()) 
                    && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权修改此对话");
            }
            
            // 更新标题
            String title = body.get("title");
            if (title == null || title.isEmpty()) {
                return ResponseEntity.badRequest().body("标题不能为空");
            }
            
            conversation = conversationService.updateConversationTitle(sessionId, title);
            return ResponseEntity.ok(conversation);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }

    /**
     * 删除对话
     */
    @DeleteMapping("/{id}")
    public ResponseEntity<?> deleteConversation(@PathVariable Long id) {
        try {
            // 获取当前用户
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            User user = userService.getUserByUsername(authentication.getName());
            
            // 获取对话
            Conversation conversation = conversationService.getConversation(id);
            
            // 验证对话是否属于当前用户
            if (conversation == null || !conversation.getUserId().equals(user.getId()) 
                    && !user.getRole().equals("ROLE_ADMIN")) {
                return ResponseEntity.status(403).body("无权删除此对话");
            }
            
            // 删除对话
            boolean result = conversationService.deleteConversation(id);
            
            if (result) {
                return ResponseEntity.ok("对话删除成功");
            } else {
                return ResponseEntity.badRequest().body("对话删除失败");
            }
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Error: " + e.getMessage());
        }
    }
} 